﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;

namespace ajayumi.Platform.Win.TextBox
{
    /// <summary>
    /// NumberTextBox.cs 数字文本框
    /// Author   : 黄乙冬
    /// Date     : 2011-11-03
    /// </summary>
    public class NumberTextBox : System.Windows.Forms.TextBox
    {
        private InputType m_InputType = InputType.UFloat;
        [DefaultValue(InputType.UFloat)]
        [Description("允许输入的类型")]
        public InputType InputType
        {
            get
            { return this.m_InputType; }
            set
            { this.m_InputType = value; }
        }

        protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
        {
            base.OnKeyPress(e);
            switch (this.InputType)
            {
                case InputType.UInt:
                    //如果输入的不是数字键，也不是回车键、Backspace键，则取消该输入
                    if (!(Char.IsNumber(e.KeyChar)) &&
                        e.KeyChar != (char)13 &&
                        e.KeyChar != (char)8)
                    {
                        e.Handled = true;
                    }
                    break;
                case InputType.UFloat:
                    //如果输入的不是数字键，也不是回车键、Backspace键、.键，则取消该输入
                    if (!(Char.IsNumber(e.KeyChar)) &&
                        e.KeyChar != (char)13 &&
                        e.KeyChar != (char)8 &&
                        e.KeyChar != (char)46
                        )
                    {
                        e.Handled = true;
                    }
                    else if (e.KeyChar == (char)46 && this.Text.Contains('.'))
                    { e.Handled = true; }
                    break;
                default:
                    break;
            }

        }
    }

    public enum InputType
    {
        /// <summary>
        /// 无符号整型
        /// </summary>
        UInt,
        /// <summary>
        /// 无符号浮点型
        /// </summary>
        UFloat
    }
}
